<template>
  <div class="financial-tools">
    <div class="tools-header">
      <h3>金融工具</h3>
      <div class="tools-tabs">
        <button 
          v-for="tool in availableTools" 
          :key="tool.id"
          :class="{ active: activeTool === tool.id }"
          @click="activeTool = tool.id"
          class="tool-tab"
        >
          <i :class="tool.icon"></i>
          {{ tool.name }}
        </button>
      </div>
    </div>
    
    <div class="tool-content">
      <!-- 复利计算器 -->
      <div v-if="activeTool === 'compoundInterest'" class="calculator">
        <div class="input-group">
          <label>本金（元）</label>
          <input v-model.number="compoundParams.principal" type="number" placeholder="输入本金金额" />
        </div>
        <div class="input-group">
          <label>年化收益率（%）</label>
          <input v-model.number="compoundParams.rate" type="number" step="0.1" placeholder="输入年化收益率" />
        </div>
        <div class="input-group">
          <label>投资年限</label>
          <input v-model.number="compoundParams.years" type="number" placeholder="输入投资年限" />
        </div>
        <div class="input-group">
          <label>每年追加金额（元）</label>
          <input v-model.number="compoundParams.additional" type="number" placeholder="可选：每年追加投资" />
        </div>
        <button @click="calculateCompoundInterest" class="calculate-btn">计算收益</button>
        
        <div v-if="compoundResult" class="result">
          <h4>计算结果</h4>
          <p>最终金额：<strong>{{ compoundResult.finalAmount.toLocaleString() }} 元</strong></p>
          <p>总收益：<strong>{{ compoundResult.totalEarnings.toLocaleString() }} 元</strong></p>
          <p>年化复合收益率：<strong>{{ compoundResult.annualReturn.toFixed(2) }}%</strong></p>
        </div>
      </div>

      <!-- 风险评估问卷 -->
      <div v-if="activeTool === 'riskAssessment'" class="questionnaire">
        <div class="question" v-for="(question, index) in riskQuestions" :key="index">
          <h4>{{ question.question }}</h4>
          <div class="options">
            <label v-for="option in question.options" :key="option.value">
              <input 
                type="radio" 
                :name="'q' + index" 
                :value="option.value" 
                v-model="riskAnswers[index]"
              />
              {{ option.text }}
            </label>
          </div>
        </div>
        <button @click="calculateRiskProfile" class="calculate-btn">评估风险承受能力</button>
        
        <div v-if="riskResult" class="result">
          <h4>风险评估结果</h4>
          <p>风险承受能力：<strong :class="riskResult.level">{{ riskResult.levelText }}</strong></p>
          <p>建议投资组合：{{ riskResult.recommendedPortfolio }}</p>
          <p>适合产品类型：{{ riskResult.suitableProducts }}</p>
        </div>
      </div>

      <!-- 收益模拟器 -->
      <div v-if="activeTool === 'incomeSimulator'" class="simulator">
        <div class="scenario-selector">
          <label>选择模拟场景：</label>
          <select v-model="selectedScenario">
            <option value="conservative">保守型投资</option>
            <option value="balanced">平衡型投资</option>
            <option value="aggressive">进取型投资</option>
          </select>
        </div>
        
        <div class="simulation-inputs">
          <div class="input-group">
            <label>初始投资（元）</label>
            <input v-model.number="simulationParams.initialInvestment" type="number" />
          </div>
          <div class="input-group">
            <label>每月追加（元）</label>
            <input v-model.number="simulationParams.monthlyAddition" type="number" />
          </div>
          <div class="input-group">
            <label>模拟年限</label>
            <input v-model.number="simulationParams.years" type="number" />
          </div>
        </div>
        
        <button @click="runSimulation" class="calculate-btn">开始模拟</button>
        
        <div v-if="simulationResult" class="result">
          <h4>模拟结果</h4>
          <div class="simulation-chart">
            <div class="chart-bar" v-for="(year, index) in simulationResult.yearlyResults" :key="index">
              <div class="bar-label">第{{ index + 1 }}年</div>
              <div class="bar-container">
                <div 
                  class="bar" 
                  :style="{ width: (year.value / simulationResult.yearlyResults[simulationResult.yearlyResults.length - 1].value * 100) + '%' }"
                ></div>
              </div>
              <div class="bar-value">{{ year.value.toLocaleString() }}元</div>
            </div>
          </div>
          <p>最终资产：<strong>{{ simulationResult.finalValue.toLocaleString() }} 元</strong></p>
          <p>总收益：<strong>{{ simulationResult.totalEarnings.toLocaleString() }} 元</strong></p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';

// 工具定义
const availableTools = [
  { id: 'compoundInterest', name: '复利计算器', icon: 'icon-calculator' },
  { id: 'riskAssessment', name: '风险评估', icon: 'icon-warning' },
  { id: 'incomeSimulator', name: '收益模拟', icon: 'icon-chart' }
];

const activeTool = ref('compoundInterest');

// 复利计算器逻辑
const compoundParams = ref({
  principal: 10000,
  rate: 8,
  years: 10,
  additional: 0
});

const compoundResult = ref<any>(null);

const calculateCompoundInterest = () => {
  const { principal, rate, years, additional } = compoundParams.value;
  let amount = principal;
  
  for (let i = 0; i < years; i++) {
    amount = amount * (1 + rate / 100) + additional;
  }
  
  const totalEarnings = amount - principal - (additional * years);
  const annualReturn = (Math.pow(amount / principal, 1 / years) - 1) * 100;
  
  compoundResult.value = {
    finalAmount: Math.round(amount * 100) / 100,
    totalEarnings: Math.round(totalEarnings * 100) / 100,
    annualReturn: Math.round(annualReturn * 100) / 100
  };
};

// 风险评估问卷逻辑
const riskQuestions = [
  {
    question: '您的投资经验如何？',
    options: [
      { value: 1, text: '没有投资经验' },
      { value: 2, text: '有一些投资经验' },
      { value: 3, text: '有丰富投资经验' }
    ]
  },
  {
    question: '您能承受的最大投资损失是多少？',
    options: [
      { value: 1, text: '不能承受任何损失' },
      { value: 2, text: '能承受10%以内的损失' },
      { value: 3, text: '能承受30%以上的损失' }
    ]
  },
  {
    question: '您的投资期限是多久？',
    options: [
      { value: 1, text: '1年以内' },
      { value: 2, text: '1-3年' },
      { value: 3, text: '3年以上' }
    ]
  }
];

const riskAnswers = ref<number[]>([]);
const riskResult = ref<any>(null);

const calculateRiskProfile = () => {
  const totalScore = riskAnswers.value.reduce((sum, score) => sum + score, 0);
  
  let level, levelText, recommendedPortfolio, suitableProducts;
  
  if (totalScore <= 4) {
    level = 'conservative';
    levelText = '保守型';
    recommendedPortfolio = '债券70% + 货币基金20% + 股票10%';
    suitableProducts = '国债、货币基金、保本理财';
  } else if (totalScore <= 7) {
    level = 'balanced';
    levelText = '平衡型';
    recommendedPortfolio = '债券50% + 股票40% + 其他10%';
    suitableProducts = '混合基金、指数基金、蓝筹股';
  } else {
    level = 'aggressive';
    levelText = '进取型';
    recommendedPortfolio = '股票60% + 其他高风险资产30% + 债券10%';
    suitableProducts = '成长股、科技股、另类投资';
  }
  
  riskResult.value = { level, levelText, recommendedPortfolio, suitableProducts };
};

// 收益模拟器逻辑
const selectedScenario = ref('balanced');
const simulationParams = ref({
  initialInvestment: 50000,
  monthlyAddition: 2000,
  years: 5
});

const simulationResult = ref<any>(null);

const scenarioReturns = {
  conservative: { min: 3, max: 6 },
  balanced: { min: 6, max: 10 },
  aggressive: { min: 10, max: 15 }
};

const runSimulation = () => {
  const { initialInvestment, monthlyAddition, years } = simulationParams.value;
  const returns = scenarioReturns[selectedScenario.value as keyof typeof scenarioReturns];
  
  const yearlyResults = [];
  let currentValue = initialInvestment;
  
  for (let i = 0; i < years; i++) {
    // 模拟年化收益率（在范围内随机波动）
    const annualReturn = returns.min + Math.random() * (returns.max - returns.min);
    currentValue = currentValue * (1 + annualReturn / 100) + (monthlyAddition * 12);
    
    yearlyResults.push({
      year: i + 1,
      value: Math.round(currentValue * 100) / 100,
      return: Math.round(annualReturn * 100) / 100
    });
  }
  
  const totalEarnings = currentValue - initialInvestment - (monthlyAddition * 12 * years);
  
  simulationResult.value = {
    finalValue: Math.round(currentValue * 100) / 100,
    totalEarnings: Math.round(totalEarnings * 100) / 100,
    yearlyResults
  };
};
</script>

<style scoped>
.financial-tools {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  margin: 16px 0;
  background: #fafafa;
}

.tools-header {
  margin-bottom: 16px;
}

.tools-header h3 {
  margin: 0 0 12px 0;
  color: #333;
  font-size: 18px;
}

.tools-tabs {
  display: flex;
  gap: 8px;
}

.tool-tab {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  transition: all 0.3s;
}

.tool-tab.active {
  background: #1976d2;
  color: white;
  border-color: #1976d2;
}

.tool-content {
  min-height: 300px;
}

.input-group {
  margin-bottom: 12px;
}

.input-group label {
  display: block;
  margin-bottom: 4px;
  font-weight: 500;
  color: #555;
}

.input-group input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.calculate-btn {
  padding: 10px 20px;
  background: #1976d2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 12px;
}

.result {
  margin-top: 20px;
  padding: 16px;
  background: white;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
}

.result h4 {
  margin: 0 0 12px 0;
  color: #333;
}

.conservative { color: #4caf50; }
.balanced { color: #ff9800; }
.aggressive { color: #f44336; }

.simulation-chart {
  margin: 16px 0;
}

.chart-bar {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.bar-label {
  width: 60px;
  font-size: 12px;
  color: #666;
}

.bar-container {
  flex: 1;
  height: 20px;
  background: #f0f0f0;
  margin: 0 8px;
  border-radius: 2px;
  overflow: hidden;
}

.bar {
  height: 100%;
  background: linear-gradient(90deg, #1976d2, #64b5f6);
  transition: width 0.3s;
}

.bar-value {
  width: 80px;
  font-size: 12px;
  text-align: right;
  color: #666;
}

.question {
  margin-bottom: 20px;
}

.question h4 {
  margin: 0 0 8px 0;
  color: #333;
}

.options label {
  display: block;
  margin-bottom: 8px;
  cursor: pointer;
}

.options input {
  margin-right: 8px;
}
</style>